package com.miku.web.controller;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.miku.common.WebController;
import com.miku.sys.config.SessionKeyDefine;
import com.miku.sys.dao.SysUserDaoI;
import com.miku.sys.security.realm.FormAuthenticationFilter;
import com.miku.sys.security.realm.SystemAuthorizingRealm.Principal;
import com.miku.sys.services.SystemUserServiceI;
import com.miku.sys.utils.UserUtils;
import com.miku.utils.CacheUtils;
import com.miku.utils.CookieUtils;

/**
 * 登录Controller
 */
@Controller("webLoginController")
@RequestMapping("${web.url.root}")
public class WebLoginController extends WebController{
	@Autowired SysUserDaoI userDao;
	@Autowired SystemUserServiceI registerService;
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(String u,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String requestURI = u;
		if(requestURI != null)
			UserUtils.getSession().setAttribute(SessionKeyDefine.requestURI, requestURI.replaceAll("&amp;", "&"));
		
		if(requestURI == null)
			requestURI = "/";
		
		model.put("urlString", requestURI);
		
		Principal principal = UserUtils.getPrincipal();
		//System.out.println("进入首页");
		logger.debug("进入登录~~~~~~~~requestURI = " + requestURI);
		
		// 如果已登录，再次访问主页，则退出原账号。
//		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
//			CookieUtils.setCookie(response, "LOGINED", "false");
//		}
		
		// 如果已经登录，则跳转到web的首页
		if(principal != null){
			log("已经登录了web：", principal);
			return "redirect:" + requestURI;
		}
		return "web/sysLogin";
	}

	/**
	 * 登录失败，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginFail(String u,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String urlString = u ;
		Principal principal = UserUtils.getPrincipal();
		// 如果已经登录，则跳转到管理首页
		if(principal != null){
			return "redirect:" + webUrlRoot + webUrlHome;
		}

		logger.debug("登录失败...");
		String username = WebUtils.getCleanParam(request, org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		boolean rememberMe = WebUtils.isTrue(request, org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String exception = (String)request.getAttribute(org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
		String message = (String)request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);
		
		if (org.apache.commons.lang3.StringUtils.isBlank(message) || org.apache.commons.lang3.StringUtils.equals(message, "null")){
			message = "用户或密码错误, 请重试.";
		}

		model.addAttribute(org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
		model.addAttribute(org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MOBILE_PARAM, mobile);
		model.addAttribute(org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
		model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);
		
		// 非授权异常，登录失败，验证码加1。
		if (!UnauthorizedException.class.getName().equals(exception)){
			model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
		}
		
		// 验证失败清空验证码
		//request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
		
		// 如果是手机登录，则返回JSON字符串
//		if (mobile){
//	        return renderString(response, model);
//		}
		model.put("urlString", urlString);
		return "web/sysLogin";
	}

	/**
	 * 登录成功，进入管理首页
	 */
//	@RequestMapping("")
//	public String index(HttpServletRequest request, HttpServletResponse response) {
//		Principal principal = UserUtils.getPrincipal();
//		
//		//UserUtils.getSubject().checkPermission("editor");
//		// 登录成功后，验证码计算器清零
//		//isValidateCodeLogin(principal.getLoginName(), false, true);
//		
//		// 如果已登录，再次访问主页，则退出原账号。
//		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
//			String logined = CookieUtils.getCookie(request, "LOGINED");
//			if (StringUtils.isBlank(logined) || "false".equals(logined)){
//				CookieUtils.setCookie(response, "LOGINED", "true");
//			}else if (StringUtils.equals(logined, "true")){
//				UserUtils.getSubject().logout();
//				return "redirect:" + webUrlRoot + "/login";
//			}
//		}
//		
//		return "redirect:" + webUrlRoot + "/search";
//	}
	
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
		if (org.apache.commons.lang3.StringUtils.isNotBlank(theme)){
			CookieUtils.setCookie(response, "theme", theme);
		}else{
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:"+request.getParameter("url");
	}
	
	/**
	 * 是否是验证码登录
	 * @param useruame 用户名
	 * @param isFail 计数加1
	 * @param clean 计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
		Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");
		if (loginFailMap==null){
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum==null){
			loginFailNum = 0;
		}
		if (isFail){
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean){
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}
	
	/**
	 * 
	 *注册
	 */
	@RequestMapping(value = "/register/homePage", method = RequestMethod.GET)
	public String registerHomePage(String u,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String urlString = u ;
		//logger.debug(urlString+"-----url");
		model.put("urlString", urlString);
		return "web/sysRegister";
	}
	
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(String u,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String urlString = u ;
		String email = request.getParameter("email");
		String password	= request.getParameter("password");
		String nickname = request.getParameter("email");
		registerService.register(request,email, password,nickname);
		
		logger.debug(urlString+"-----url");
		return  "redirect:"+ urlString;
	}
	
	@ResponseBody
	@RequestMapping(value = "/isExistsEmail", method = RequestMethod.POST)
	public String isExistsEmail(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		JSONObject json = new JSONObject();
		String email = request.getParameter("email");
		boolean isExists = !(registerService.isExistsEmail(email));//true 显示message ;false 不显示
		//logger.debug(isExists+"-----isExists");
		/*String isEx = isExists +"";
		model.put("isEx", isEx);*/
		json.put("valid",isExists);
		return json.toJSONString();
	}
	
	/**
	 * 退出
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(String u,HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		String lastRequestURI = u ;
		UserUtils.getSubject().logout();
		return  "redirect:"+ lastRequestURI;
	}
	/*
	@ResponseBody
	@RequestMapping("/test")
	public String t(){
		String entity = "{\"kf_account\" :\"kf2001@gh_23209dd06bb6\",\"openid\" : \"orG5huAd_13GLnBP0IOvm1BR5Jng\"}";
		logger.debug("entity = " + entity);
		WxRespValue r = WxUtils.callAPIPost("https://api.weixin.qq.com/customservice/kfsession/create?access_token=[ACCESS_TOKEN]",
				entity,
				"ACCESS_TOKEN=" + WxAccessTokenManager.getAccessTokenStatic());
		logger.debug(JSON.toJSONString(r));
		return null;
	}*/
}
